import { ChatService } from '../services/chat.js'
import logger from '../services/logger.js'

const chatService = new ChatService()

export const sendMessage = async (req, res, next) => {
  try {
    // 从消息对象中获取内容
    const messageObj = req.method === 'GET' ? req.query.message : req.body.message
    const message = messageObj?.content || messageObj
    const history = Array.isArray(req.body?.history) ? req.body.history : []

    if (!message) {
      throw new Error('Message content is required')
    }

    // 确保消息内容是字符串
    const messageContent = typeof message === 'string' ? 
      message : 
      Buffer.from(JSON.stringify(message), 'utf8').toString('utf8')

    logger.info('Processing chat message:', { 
      content: messageContent,
      history 
    })

    // 设置 SSE 头
    res.writeHead(200, {
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'X-Accel-Buffering': 'no'
    })

    let answer = ''
    try {
      const responseStream = await chatService.generateResponseStream(messageContent, history)
      logger.info('Response stream created')

      for await (const chunk of responseStream) {
        if (chunk.type === 'sources') {
          res.write(`data: ${JSON.stringify({ type: 'sources', data: chunk.data })}\n\n`)
        } else if (chunk.type === 'text') {
          answer += chunk.data
          res.write(`data: ${JSON.stringify({ type: 'text', data: chunk.data })}\n\n`)
        }
      }

      // 构建新的历史记录
      const newHistory = [
        ...history,
        { 
          id: Date.now().toString(),
          role: 'user', 
          content: messageContent,
          time: new Date()
        },
        {
          id: (Date.now() + 1).toString(),
          role: 'assistant', 
          content: answer,
          time: new Date()
        }
      ].slice(-10)

      res.write(`data: ${JSON.stringify({ type: 'history', data: newHistory })}\n\n`)
      res.end()

    } catch (error) {
      logger.error('Stream processing error:', {
        error: error.message,
        stack: error.stack,
        message: messageContent,
        history
      })
      res.write(`data: ${JSON.stringify({ type: 'error', data: error.message })}\n\n`)
      res.end()
    }
  } catch (error) {
    logger.error('Request processing error:', error)
    next(error)
  }
}

// 处理聊天请求
export const chat = async (req, res, next) => {
  try {
    const { message, history } = req.body
    
    // 验证消息格式
    if (!message?.content || !message?.role) {
      return res.status(400).json({
        message: '无效的消息格式'
      })
    }

    // 获取当前问题
    const currentQuestion = message.content.trim()
    
    // 构建历史消息
    const conversationHistory = history.map(msg => 
      `${msg.role}: ${msg.content}`
    ).join('\n')

    logger.info('Processing question:', {
      question: currentQuestion,
      historyLength: history.length
    })

    // 获取相关文档片段
    const relevantChunks = await vectorStore.search({
      query: currentQuestion,
      limit: 5
    })

    // 构建上下文
    const context = relevantChunks.data
      .map(chunk => chunk.content)
      .join('\n\n')

    // 构建 prompt
    const prompt = `
对话历史:
${conversationHistory}

参考文档内容:
${context}

用户问题: ${currentQuestion}

请根据上述文档内容回答用户的最新问题。如果无法从文档中找到答案，请明确说明。
回答时要考虑对话的上下文，确保回答的连贯性。
`

    // 生成回答
    const answer = await modelService.generateAnswer(prompt)

    // 构建响应消息
    const responseMessage = {
      id: Date.now().toString(),
      content: answer,
      role: 'assistant',
      time: new Date(),
      sources: relevantChunks.data.map(chunk => ({
        content: chunk.content,
        score: chunk.score
      }))
    }

    res.json({
      message: responseMessage,
      history: [...history, message, responseMessage]
    })

  } catch (error) {
    logger.error('Chat failed:', {
      error: error.message,
      stack: error.stack
    })
    next(error)
  }
} 